package org.hu.vhr.controller.advertise;

import jdk.jfr.internal.SecuritySupport;
import org.apache.poi.util.IOUtils;
import org.hu.vhr.model.RespBean;
import org.hu.vhr.util.ParseUtil;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/advertise")
public class AdvertiseController {
    @RequestMapping("/import")
    public String upload(MultipartFile file) throws Exception {
        //保存本地文件
        file.transferTo(new File("D:\\vuehr\\public\\" + file.getOriginalFilename()));
        //解析
        JSONObject res = ParseUtil.Parser("D:/jianli/" + file.getOriginalFilename());
        res.put("filename", file.getOriginalFilename());
        System.out.println(res);
        return res.toString();
    }

    @RequestMapping("/open")
    public void open(HttpServletResponse response,String filename) throws Exception {
        String filePath = "D:/";
        File file = new File(filePath + "/" + filename);
        if (file.exists()) { //判断文件父目录是否存在
//            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
